<template>
    <div class="flex_col flex_start_self m5 p10 card">
        <label class="flex_center_self">串口设置</label>
        <div class="flex_row_center mt5">
            <label>端口</label>
            <el-select class="input_w ml5" v-model="ctx.current">
                <el-option v-for="(item, index) in ctx.ports" :key="index" :label="item" :value="item" />
            </el-select>
            <el-button class="ml5" type="primary">刷新</el-button>
        </div>
        <div class="flex_row_center mt5">
            <el-button type="primary" @click="onClickOpen">{{ ctx.open_text }}</el-button>
            <el-button @click="onClickPing" type="info">Ping</el-button>
        </div>
    </div>
</template>

<script lang="ts" setup>
import { reactive } from 'vue';
import conn_port from '../service/conn_port';
import { runAction } from '../utils/ui';
import service from '../service/service';


interface Ctx {
    ports: string[],
    open_text: string,
    current: string,
}

const ctx = reactive<Ctx>({
    ports: [],
    open_text: '打开',
    current: '',
});

async function onClickOpen() {
    const ret = await conn_port.is_open();
    if (ret) {
        await conn_port.close();
        await init();
    } else {
        await runAction('串口', '打开', async () => {
            const name = ctx.current;
            if (name.length == 0) {
                throw '没有串口';
            }
            await conn_port.open(ctx.current, 115200);
            await init();
        });
    }
}

async function onClickPing() {
    runAction('串口', 'Ping', async () => {
        await service.ping();
    });
}

async function init() {
    const ret = await conn_port.is_open();
    if (ret) {
        ctx.open_text = '关闭';
    } else {
        ctx.open_text = '打开';
    }
}

async function refresh() {
    const ports = await conn_port.available_ports();
    ctx.ports = ports;
    if (ports.length != 0) {
        ctx.current = ports[0];
    }
}

refresh();
init();

</script>
